<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import HDrawer from '@/components/common/drawer/HDrawer'
// import {
//   useUpdateOrderInfo,
//   useGetOrderInfoBeforeEdit,
// } from '@/services/pages/order/useOrderDetail'

// const { form, loading: updateInfoLoading, save, resetForm } = useUpdateOrderInfo()
import * as _ from 'lodash'
import { empPageSelecct } from '@/api/organize'
import useFactorySelectPageService from '@/views/order/new/services/factorySelectPage'
import {
  workModuleTypePageSelect,
  workModuleWayPageSelect,
  SearchCustomerInfo,
  orderUpdateInfo,
} from '@/api/order'
import { ElMessage } from 'element-plus'
import { OrderDetail } from '@/viwes/order/list/odetail/types'
import SingleAddress from '@/components/address/singleAddress.vue'

const CascaderProps = ref({
  value: 'id',
  label: 'name',
  children: 'selectVos',
  disabled: 'select',
  checkStrictly: true,
})

const basicData = ref<OrderDetail | null>(null)

const fileList = ref([])

const visible = ref(false)

const updateInfoLoading = ref(false)

const sources = ref([
  { title: '平台系统报单', value: 1 },
  { title: '扫码报单', value: 2 },
  { title: '小程序报单', value: 3 },
  { title: 'APP报单', value: 4 },
  { title: '平台代商家报单', value: 7 },
  { title: '乐开伙伴云', value: 9 },
])

// 规则
const rules = ref({
  contactsPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  otherPhone: [
    {
      pattern: /^\d{3,4}$/,
      message: '分机号应为3-4位数字',
      trigger: 'blur',
    },
  ],
})

// 获取图片
let pass = ref(true)
const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
  if (fileList.value.length >= 10) {
    if (pass.value) {
      ElMessage({
        showClose: true,
        message: `数量不能超过10!`,
        type: 'error',
        duration: 3000,
      })
      pass.value = false
    }

    return
  }
  pass.value = true
  let { uid, name } = uploadFile.raw
  let tmp = {
    uid,
    name,
    img: window.URL.createObjectURL(uploadFile.raw),
    file: uploadFile.raw,
    upDatatime: new Date(Date.now()).toISOString().split('T')[0],
  }
  fileList.value.push(tmp)
}
// 删除图片
const deleteItem = (index) => {
  fileList.value = fileList.value.filter((o, i) => i != index)
}

const dialogContract = ref(false) //文件查看弹窗
const file = ref() //文件
// 查看图片
const lookFile = (val) => {
  file.value = val
  dialogContract.value = true
}

//监听弹窗关闭时销毁 iframe内存
watch(dialogContract, (n) => {
  if (!n) {
    file.value = 'about:blank'
  }
})

/**
 * 工单客服组下拉列表查询
 */
const loading = ref(false)
const customers = ref([])
const getworkTeamPageSelect = _.throttle((val: string) => {
  let data = {
    limit: 0,
    name: val,
    page: 0,
  }
  loading.value = true
  empPageSelecct(data).then((res) => {
    if (res.data.success) {
      customers.value = res.data.data.rows
    }
    loading.value = false
  })
}, 500)

const valueSele = ref('')
const changeValue = () => {
  getFactorySelectPageFn({ limit: 0, name: valueSele.value, page: 0 })
}

// 使用品牌商家下拉数据服务
const { factoryOptional, getFactorySelectPageLoading, getFactorySelectPageFn } =
  useFactorySelectPageService

//工单分类下拉远程搜索
const inputChangeType = async (val) => {
  if (basicData.moduleId) {
    await getworkModuleTypePageSelect(val, basicData.moduleId)
  }
}

// 处理方式下拉远程搜索
const inputChangeMethod = async (val) => {
  if (val && basicData.moduleId) {
    await getworkModuleWayPageSelect(val, basicData.moduleId)
  }
}

const methodss = ref([])
//  通过模块id 获取处理方式
const getworkModuleWayPageSelect = async (val, id) => {
  let data = {
    limit: 0,
    name: val,
    page: 0,
  }
  const res = await workModuleWayPageSelect(data, id)
  methodss.value = res.data.data.rows
}
// 工单分类下拉框出现/隐藏时触发
const showType = ref(false)
const changeType = async () => {
  showType.value = !showType.value
  if (!showType.value) {
    if (!(basicData.value.type instanceof Array)) {
      await getworkModuleTypePageSelect('', basicData.value.moduleId)
    }
  }
}
// 处里方式下拉框出现/隐藏时触发
const changeMmethod = async () => {
  showType.value = !showType.value
  if (!showType.value) {
    if (!(basicData.value.method instanceof Array)) {
      await getworkModuleWayPageSelect('', basicData.value.moduleId)
    }
  }
}

const types = ref([])
//工单分类下拉数据
const getworkModuleTypePageSelect = async (val, id) => {
  let data = {
    limit: 0,
    name: val,
    page: 0,
  }
  const res = await workModuleTypePageSelect(data, id)
  types.value = res.data.data.rows
}
const open = (params) => {
  visible.value = true
  basicData.value = { ...params }
  fileList.value = params.orderImages.map((item) => ({
    name: '',
    img: item,
  }))
}
const emits = defineEmits(['update'])
// 保存
const onSubmit = async () => {
  const data = { ...basicData.value }
  const type = data.type
  const method = data.method
  // 工单模块分类
  if (type?.length > 0) {
    type.map((o, i) => {
      if (i == 0) {
        data.oneTypeId = o
      }
      if (i == 1) {
        data.twoWayId = o
      }
      if (i == 2) {
        data.threeTypeId = o
      }
    })
  }
  // 工单模块方式
  if (method?.length > 0) {
    method.map((o, i) => {
      if (i == 0) {
        data.oneWayId = o
      }
      if (i == 1) {
        data.twoWayId = o
      }
      if (i == 2) {
        data.threeWayId = o
      }
    })
  }
  // 判断是否有图片
  if (fileList.value?.length > 0) {
    let imageList = fileList.value.map((o) => {
      return o.file
    })
    // 上传图片
    data.imageVos = []
    const orderAnnexUploadRes = await orderAnnexUpload(imageList)
    if (orderAnnexUploadRes.data.success) {
      for (let i = 0; i < orderAnnexUploadRes.data.data.rows.length; i++) {
        data.imageVos.push({ id: null, image: orderAnnexUploadRes.data.data.rows[i] })
      }
    } else {
      ElMessage({
        message: orderAnnexUploadRes.data.message,
        type: 'error',
      })
    }
  }

  updateInfoLoading.value = true
  const res = await orderUpdateInfo(data)
  updateInfoLoading.value = false
  if (res.data.success) {
    visible.value = false
    emits('update')
    ElMessage({
      showClose: true,
      message: '保存成功！',
      type: 'success',
      duration: 3000,
    })
  } else {
    if (res.data.isError)
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 3000,
      })
  }
}
// 地址
/**
 * 获取地址
 */

const addressRef = ref()

const handleAddressChange = () => {
  const address = addressRef.value.getSelectAddr()
  basicData.value.province = address.province
  basicData.value.area = address.area
  basicData.value.city = address.city
  basicData.value.town = address.town
}

/**
 * 清空地址
 */
const onClearAddress = () => {
  basicData.value.province = null
  basicData.value.area = null
  basicData.value.city = null
  // filterForm.value.town = ''
}
//搜索
// 输入框绑定值
const Onsearch = ref('')
// 表格数据
const gridData = ref([])
// 搜索状态
const SearchState = ref(false)
// 弹窗显示状态
const popoverVisible = ref(false)

// 搜索加载状态
const Searchloading = ref(false)

// 搜索函数
const SearchCInfo = async () => {
  Searchloading.value = true

  try {
    let name = {
      name: Onsearch.value,
    }
    const res = await SearchCustomerInfo(name)

    let response = res.data.data.row
    Searchloading.value = false

    if (response.length == 1) {
      onCustomerInfo(response[0], '', null)
      return
    }

    if (response.length > 0) {
      gridData.value = response
      SearchState.value = true
      popoverVisible.value = true
    } else {
      ElMessage.warning('未找到相关数据')
      popoverVisible.value = false
    }
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
    popoverVisible.value = false
  }
}
// 定义数据类型
interface Customer {
  userId: number
  username: string
  contacts: string
  phone: string
  province: string
  area: string
  city: string
  address: string
  extensionNbr: string
}

const onCustomerInfo = (row: Customer, column: any, event: MouseEvent) => {

  
  basicData.value.city = row.city
  basicData.value.area = row.area
  basicData.value.address = row.address
  basicData.value.province = row.province
  basicData.value.contacts = row.username
  basicData.value.contactsPhone = row.phone
  // basicData.value.extensionNbr = row.extensionNbr

  Onsearch.value = ''
  popoverVisible.value = false
}

const hideDrawer = () => {
  visible.value = false
}
defineExpose({
  open,
})
</script>

<template>
  <h-drawer
    v-model="visible"
    title="修改客户信息"
    :loading="updateInfoLoading"
    :width="800"
    unit="px"
    @close="hideDrawer"
  >
    <el-form
      ref="formInstance"
      class="modal_form_content"
      label-position="top"
      :model="basicData"
      :rules="rules"
      inline-message
      scroll-to-error
    >
      <!-- 搜索 -->

      <el-form-item label="搜索新用户" prop="source">
        <el-popover
          placement="bottom"
          :width="730"
          trigger="manual"
          v-model:visible="popoverVisible"
        >
          <template #reference>
            <div class="seach">
              <el-input
                v-model="Onsearch"
                :rows="2"
                class="form-control"
                placeholder="请输入名称"
                show-word-limit
              />
              <el-button :loading="Searchloading" type="primary" @click="SearchCInfo"
                >搜索</el-button
              >
            </div>
          </template>
          <el-table :data="gridData" v-if="SearchState" @row-click="onCustomerInfo">
            <el-table-column prop="username" label="客户名称" > </el-table-column>
            <el-table-column prop="phone" label="联系人电话"> </el-table-column>
            <el-table-column prop="province" label="市"> </el-table-column>
            <el-table-column prop="city" label="市"> </el-table-column>
            <el-table-column prop="area" label="区"> </el-table-column>
            <el-table-column width="180" prop="address" label="详细地址"> </el-table-column>

          </el-table>
        </el-popover>
      </el-form-item>

      <!-- 客户名称 -->
      <el-form-item label="客户名称" prop="source">
        <el-input
          v-model="basicData.contacts"
          disabled
          :rows="2"
          class="form-control"
          placeholder="请输入客户名称:"
          show-word-limit
        />
      </el-form-item>

      <!-- 联系人 -->
      <el-form-item label="联系人" prop="source">
        <el-input
          v-model="basicData.contacts"
          disabled
          :rows="2"
          class="form-control"
          placeholder="请输入联系人"
          show-word-limit
        />
      </el-form-item>

      <!-- 联系人电话 -->
      <el-form-item label="联系人电话" prop="contactsPhone">
        <el-input
          v-model="basicData.contactsPhone"
          disabled
          :rows="2"
          class="form-control"
          placeholder="请输入联系人电话"
          show-word-limit
        />
      </el-form-item>

      <!-- 分机号电话 -->
      <el-form-item label="分机号" prop="extensionNbr">
        <el-input
          v-model="basicData.extensionNbr"
          :rows="2"
          class="form-control"
          placeholder="请输入分机号"
          show-word-limit
        />
      </el-form-item>

      <!-- 客户地址 -->
      <el-form-item label="客户地址" prop="source">
        <!-- <SingleAddress
          ref="addrsDom"
          class="width-select"
          :address="addrs"
          @value-change="handleAddressUpdate"
        /> -->
        <!-- <SingleAddress
          style="width: 220px"
          ref="addrsDom"
          :address="addrs"
          @value-change="handleChangeAddress"
          @clear="onClearAddress"
          checkStrictly
        /> -->
        <SingleAddress
          ref="addressRef"
          :address="{
            province: basicData.province,
            city: basicData.city,
            area: basicData.area,
            town: basicData.town,
            SelectType: false, // 固定为单选
          }"
          @value-change="handleAddressChange"
        />
      </el-form-item>

      <!-- 详细地址 -->
      <el-form-item label="详细地址" prop="source">
        <el-input
          v-model="basicData.address"
          :rows="2"
          class="form-control"
          placeholder="请输入详细地址"
          show-word-limit
        />
      </el-form-item>

      <!-- 上传附件 -->
      <!-- <el-form-item label="工单图片上传附件">
                <div class="upload_file">
                  <el-upload
                    v-model="fileList"
                    :auto-upload="false"
                    :on-change="handleChange"
                    :show-file-list="false"
                    accept="image/*,.pdf"
                    action="#"
                    drag
                    multiple
                  >
                    <el-icon class="up_icon">
                      <UploadFilled />
                    </el-icon>
                    <div>点击上传图片或者文件(最多10个附件)</div>
                  </el-upload>
                  <ul class="ul_list">
                    <li v-for="(item, index) in fileList" :key="index" class="li_item">
                      <div class="li_item_left">
                        <img
                          v-if="item.name.replace(/.+\./, '') == 'pdf'"
                          :src="pdf"
                          alt=""
                          style="width: 30px; height: 30px"
                          @click.stop="lookFile(item.img)"
                        />
                        <el-image
                          v-else
                          :preview-src-list="[item.img]"
                          :src="item.img"
                          fit="contain"
                          style="width: 30px; height: 30px"
                        />
                        <span class="pic_name">{{ item.name }}</span>
                      </div>
                      <el-icon size="16" style="cursor: pointer" @click.stop="deleteItem(index)">
                        <Delete />
                      </el-icon>
                    </li>
                  </ul>
                </div>
              </el-form-item> -->
    </el-form>
    <template #footer>
      <HButton is-modal type="primary" @click="onSubmit">保存</HButton>
      <HButton is-modal @click="hideDrawer">关闭</HButton>
    </template>

    <!-- 文件查看 -->
    <el-dialog
      v-model="dialogContract"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :draggable="true"
      title="查看附件"
    >
      <iframe
        :src="`${file}`"
        frameborder="0"
        height="100%"
        style="height: 700px"
        width="100%"
      ></iframe>
    </el-dialog>
  </h-drawer>
</template>

<style scoped lang="scss">
.upload_file {
  width: 100%;

  :deep(.el-upload-dragger) {
    padding: 0;
    font-size: 12px;
    height: 40px;
    line-height: 10px !important;
    color: #999;
  }

  .up_icon {
    color: #ccc;
    font-size: 24px;
  }

  .ul_list {
    display: flex;
    max-height: 230px;
    overflow-y: auto;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-top: 10px;
    padding: 0 6px;

    .li_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border: 1px solid #e4e7ed;
      padding: 4px 10px;
      width: calc(50% - 40px);
      color: #999;
      font-size: 12px;
      margin-top: 10px;
      padding-right: 10px;
      border-radius: 2px;

      .li_item_left {
        display: flex;
        align-items: center;
        width: calc(100% - 15px);

        .pic_name {
          padding-left: 10px;
          color: #000;
          margin-right: 5px;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 70%;
          overflow: hidden;
        }
      }
    }
  }
}
.seach {
  width: 100%;
  display: flex;
  align-content: center;

  .el-button {
    width: 5rem;
    height: 1.7rem;
    margin: 0 0.4rem;
  }
}

.seach {
  display: flex;
  align-items: center;
}

.el-input {
  margin-right: 10px;
}
</style>
